import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
  getters: {
    token: state => state.user.token,
    userId: state => state.user.id,
    username: state => state.user.username
  },
  modules: {
    user: {
      namespaced: true,
      state: {
        id: localStorage.getItem('userId') || null,
        username: localStorage.getItem('username') || '',
        token: localStorage.getItem('token') || ''
      },
      mutations: {
        SET_USER_INFO (state, userInfo) {
          state.id = userInfo.id
          state.username = userInfo.username
          state.token = userInfo.token

          // 持久化存储
          localStorage.setItem('userId', userInfo.id)
          localStorage.setItem('username', userInfo.username)
          localStorage.setItem('token', userInfo.token)
        },
        CLEAR_USER_INFO (state) {
          state.id = null
          state.username = ''
          state.token = ''

          localStorage.removeItem('userId')
          localStorage.removeItem('username')
          localStorage.removeItem('token')
        }
      },
      actions: {
        // 登录成功后保存用户信息
        saveUserInfo ({ commit }, userInfo) {
          commit('SET_USER_INFO', userInfo)
        },
        // 退出登录
        logout ({ commit }) {
          commit('CLEAR_USER_INFO')
        }
      }
    }
  }
})
